package com.wymobilearchitecture.study.thread.security;

import com.example.w_library.log.WLog;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多个线程竞争锁的用法
 */
public class ReentrantLockTest01 {

    public ReentrantLockTest01(){

        final ReentrantLockTask task = new ReentrantLockTask();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                task.buyTicket();
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
    }

    /**
     * 基本用法 悲观锁
     */
    static class ReentrantLockTask{
        ReentrantLock reentrantLock = new ReentrantLock();

        public void buyTicket(){
            String name = Thread.currentThread().getName();
            try{
                reentrantLock.lock();
                WLog.e(name + " : 准备好买票..");
                Thread.sleep(1000);
                WLog.e(name + " : 买好了..");


                /**
                 * 可重入锁用法
                 */
                reentrantLock.lock();
                WLog.e(name + " : 又准备好买票..");
                Thread.sleep(1000);
                WLog.e(name + " : 又买好了..");

                reentrantLock.lock();
                WLog.e(name + " : 又准备好买票..");
                Thread.sleep(1000);
                WLog.e(name + " : 又买好了..");


            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();

                /**
                 * 最好与 lock 对应
                 */
                reentrantLock.unlock();
                reentrantLock.unlock();
            }
        }
    }
}
